import { useLoginStore } from "@/store/login";
import axios from "axios";
import qs from "qs";
import { ElLoading, ElMessage } from "element-plus";

let loadingInstance;
const debounce = ["doEdit", "doDelete"]; // 定义 debounce 数组

function startLoading() {
  loadingInstance = ElLoading.service({
    text: "加载中...",
    lock: true,
    fullscreen: true,
  });
}

const endLoading = () => {
  if (loadingInstance) loadingInstance.close();
};

const handleCode = (coding, msg) => {
  ElMessage({
    message: msg || `后端接口${code}异常`,
    type: "error",
  });
};

// 创建axios实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || "http://localhost:3000", // api 的 base_url
  timeout: 30000,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const store = useLoginStore(); // 获取 store 实例
    const token = store?.token; // 更优的获取方式
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`; // 使用 Bearer token
    }
    if (
      config.data &&
      config.headers["Content-Type"] === "application/x-www-form-urlencoded"
    ) {
      config.data = qs.stringify(config.data);
    }
    if (debounce.some((item) => config.url.includes(item))) {
      startLoading(); // 显示加载动画
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    endLoading();
    const { data, request, config } = response;
    const { coding, msg } = data;
    console.log(coding);
    if (coding === 1) {
      return data;
    } else {
      handleCode(coding, msg);
      return Promise.reject(
        "请求异常拦截:" + JSON.stringify({ url: config.url, coding, msg })
      );
    }
  },
  (error) => {
    endLoading();
    const { response, message } = error;
    if (response && response.data) {
      const { status } = response;
      handleCode(status, response.data.msg || message);
      return Promise.reject(error);
    } else {
      let errMsg = message || "后端接口未知异常";
      if (message === "Network Error") {
        errMsg = "后端接口连接异常";
      } else if (message.includes("timeout")) {
        errMsg = "后端接口请求超时";
      } else if (message.includes("Request failed with status coding")) {
        const coding = message.substr(message.length - 3);
        errMsg = `后端接口${code}异常`;
      }
      ElMessage({ message: errMsg, type: "error" });
      return Promise.reject(error);
    }
  }
);

export default instance;
